<?php
namespace app\msg\controller;



use app\msg\model\CustomerMapping;
use extra\BusinessException;
use extra\Constant;

class Customer extends Base
{

    /**
     * 新用户注册
     */
    public function setCustomer()
    {
        try{
            $mobile = $this->data['mobile']?$this->data['mobile']:'';

            if(!is_mobile($mobile)){
                BusinessException::throwException(Constant::INVALID_MOBILE);
            }

            //查询手机号是否已经注册
            $mod = new CustomerMapping();

            $data = array('mobile'=>$mobile);
            $result = $mod->getOne($data);

            //如果有注册，返回注册信息，如果没有注册，写入后返回注册ID
            if($result){
                $ret = Constant::getReturn(Constant::SUCCESS);
                $ret['data']['customer_id'] =  $result['id'];
                $ret['data']['mobile']      =  $result['mobile'];
                $ret['data']['is_exist']    =  1;
            }else{
                $customerId = $mod->genAutoIncrementId();

                $data = array(
                    'mobile'=> $mobile,
                    'id'   => $customerId,
                );
                $insertRes = $mod->insertData($data);

                //写入成功后返回用户的id和手机号
                if($insertRes){
                    $ret = Constant::getReturn(Constant::SUCCESS);
                    $ret['data']['customer_id']  =  $customerId;
                    $ret['data']['mobile']       =  $mobile;
                    $ret['data']['is_exist']     =  0;
                }else{
                    BusinessException::throwException(Constant::CUSTOMER_ADD_FAILED);
                }
            }

        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        return json($ret);
    }


    /**
     * 根据用户手机号返回用户ID
     */
    public function getCustomer()
    {
        try{

            $mobile = $this->data['mobile']?$this->data['mobile']:'';
            if(!is_mobile($mobile)){
                BusinessException::throwException(Constant::INVALID_MOBILE);
            }

            //查询手机号是否已经注册
            $mod = new CustomerMapping();

            $data = array('mobile'=>$mobile);
            $result = $mod->getOne($data);

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data']['customer_id'] =  $result['id'];

        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        return json($ret);
    }
}


















